當談到在.NET中使用LINQ(Language-Integrated Query)時,我們談論的是一種強大的語言特性,它允許我們以類似SQL的方式來查詢和操作數據集合,無論是在記憶中的集合、數組、數據庫或XML文件中。LINQ通常用於.NET框架中的C#或VB.NET等語言。
using System;
using System.Collections.Generic;
using System.Linq;
using api_demo.Models;
using Microsoft.AspNetCore.Mvc;
using Microsoft.EntityFrameworkCore;
// GET: api/users
[Route("api/users")]
[ApiController]
public class UserController : ControllerBase
{
private readonly DemoContext _context;
public UserController(DemoContext context)
{
_context = context;
}
[HttpGet]
public ActionResult<IEnumerable<Test>> GetUsers()
{
var users = _context.Test.ToList();
var response = new { result = 0, msg = "OK", data = users };
return Ok(response);
}
// GET: api/users/5
[HttpGet("{id}")]
public ActionResult<Test> GetUser(int id)
{
var user = _context.Test.FirstOrDefault(u => u.user_id == id);
if (user == null)
{
var notFoundResponse = new { result = -1, msg = "User not found" };
return NotFound(notFoundResponse);
}
var response = new { result = 0, msg = "OK", data = user };
return Ok(response);
}
// POST: api/users
[HttpPost]
public ActionResult<Test> CreateUser(Test user)
{
_context.Test.Add(user);
_context.SaveChanges();
var response = new { result = 0, msg = "OK", data = user };
return CreatedAtAction(nameof(GetUser), new { id = user.user_id }, response);
}
// PUT: api/users/5
[HttpPut("{id}")]
public IActionResult UpdateUser(int id, Test user)
{
if (id != user.user_id)
{
var badRequestResponse = new { result = -1, msg = "Invalid request" };
return BadRequest(badRequestResponse);
}
_context.Entry(user).State = EntityState.Modified;
try
{
_context.SaveChanges();
}
catch (DbUpdateConcurrencyException)
{
if (!_context.Test.Any(u => u.user_id == id))
{
var notFoundResponse = new { result = -1, msg = "User not found" };
return NotFound(notFoundResponse);
}
else
{
throw;
}
}
var response = new { result = 0, msg = "OK" };
return Ok(response);
}
// DELETE: api/users/5
[HttpDelete("{id}")]
public IActionResult DeleteUser(int id)
{
var user = _context.Test.FirstOrDefault(u => u.user_id == id);
if (user == null)
{
var notFoundResponse = new { result = -1, msg = "User not found" };
return NotFound(notFoundResponse);
}
_context.Test.Remove(user);
_context.SaveChanges();
var response = new { result = 0, msg = "OK" };
return Ok(response);
}
}
以下是一個.NET API的範例,介紹了如何使用它來執行刪除、增加、更新和搜索操作。
那今天就到這裡囉 掰掰~